<?php
namespace app\index\controller;

use app\admin\model\Lunbo;
use app\admin\model\User;
use verify\code;
use think\Controller;
use think\Session;
use think\Validate;

use Flc\Alidayu\Client;
use Flc\Alidayu\App;
use Flc\Alidayu\Requests\AlibabaAliqinFcSmsNumSend;


class LoginController extends Controller
{
    public function _initialize()
    {
        parent::_initialize();
        if (Session::get('user_id') || cookie('user_id'))
        {
            Session::set('user_id', decode(cookie('user_id')));
            return $this->redirect(url('/user'));
        }
        /*if (Session::get('user_id'))
            return $this->redirect(url('/user'));*/
        //1.取出配置项内容  -- 在extra/web.php中
        $config = config('web');
        $this->assign('config', $config);
        //3.轮播图
        $lunbo = (new Lunbo())->_list();
        $this->assign('lunbo', $lunbo);
    }
    //后台登录首页
    public function index()
    {
        $data = input('post.');
        if (isset($data) && !empty($data)) {
            $rules = [
                'username'=>'require|max:90',
                'password'=>'require'
            ];
            $message = [
                'username.require' => '用户名不能为空',
                'username.max' => '用户名不能超过 30 个字符',
                'password.require' => '密码不能为空',
            ];
            //$data = $_POST;
            $validate = new Validate($rules, $message);
            if (!$validate->check($data)) { // 验证不通过
                return $this->error($validate->getError()); //return back()->with('errors', $validate->getError());
            }
            //1.检测验证码
            $model = new User();
            /*if ( !$model->check_verify($data['code']) ) {
                return $this->error('验证码输入有误');
            }*/
            //2.检测用户名和密码
            if ( !$user = $model->check_user($data['username'], $data['password'])) {
                return $this->error('用户名或密码输入有误');
            }
            //3. 验证通过设置session
            Session::set('user_id', $user['id']);
            cookie('user_id', encode($user['id']), 86400*30);
            Session::set('user_name', $user['username']);
            $this->redirect(url('/user'));
            //$this->success('登录成功', '/user');
        }else {
            //return $this->fetch();
            return $this->fetch('login');
        }
    }

    // 注册
    public function register()
    {
        if (request()->isPost())
        {
            $data = input('post.');
            //1.验证码是否正确
            if ( empty($data['code']) || Session::get('code') != $data['code']) return $this->error('手机验证码输入有误');
            $rs = (new User())->data_verify($data);
            if ($rs>0) {
                Session::set('user_id', $rs);
                cookie('user_id', encode($rs), 86400*30);
                $this->success('注册成功', '/user');
            }else {
                $this->error($rs);
            }
        }
        else
        {
            return $this->fetch();
        }
    }

    public function code()
    {
        //根据手机号 发送验证码
        if (request()->isPost())
        {
            $data = input('post.username');
            if ( !isMobile($data) ) return $this->error('手机号码输入有误');
            //随机生成4位验证码
            $str = '0123456789';
            $code = ''; //生成的验证码
            for ($i=0; $i<4; $i++)
            {
                $code .= $str[mt_rand(0, 9)];
            }
            /*$code = '1234';
            Session::set('code', $code);
            return $this->success('发送成功');*/
            //-------------------------------  阿里大于发送验证码 start ------------------------------------------------
            // 1.读取 配置信息 extra/alidayu.php 中
            $config = config('alidayu');

            // 阿里大鱼发送短信对象
            $client = new Client(new App($config));
            $req    = new AlibabaAliqinFcSmsNumSend;

            //阿里大鱼短信参数规则：
            $para = ['code' => $code];
            $req->setRecNum($data)
                ->setSmsParam($para)
                ->setSmsFreeSignName($config['signature'])
                ->setSmsTemplateCode($config['template_id']);
            $resp = $client->execute($req);
            //--- 判断参数是否有误 //stdClass Object ( [code] => 15 [msg] => Remote service error [sub_code] => isv.SMS_SIGNATURE_ILLEGAL [sub_msg] => 短信签名不合法 [request_id] => 11if1p4b2l7ps )
            if (isset($resp->code)) {
                $msg = isset($resp->sub_msg) ? $resp->sub_msg : '参数配置有误';
                return $this->error($msg);
            }
            if ( $resp->result->err_code != 0 )
            {//发送失败
                return $this->error('发送失败');
            }
            else
            {
                Session::set('code', $code);
                return $this->success('发送成功');
            }
            //-------------------------------  阿里大于发送验证码 end  ------------------------------------------------
        }
    }

    //验证码显示
    public function verify()
    {
        //$code = new Code();
        $code = new code();
        $code->make();
    }
}
